package com.byq.mm.smartlib.component;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.byq.mm.abstractx.cluster.server.ClusterServer;
import com.byq.mm.abstractx.cluster.server.DeviceServer;
import com.byq.mm.abstractx.cluster.server.access.SecuredServer;
import com.byq.mm.smartlib.R;
import com.byq.mm.smartlib.cluster.activity.server.ServerClusterActivityManager;

import com.byq.mm.smartlib.tools.IconManager;

public class TreeView extends ListView {
    
    private final int SELECTED_TOP = 150;

    private TreeCallBack callBack;

    private TreeAdapter adapter;

    private int selectedPosition = -1;

    public TreeView(Context context, TreeCallBack c) {
        super(context);
        this.callBack = c;
        if (callBack == null)
            throw new NullPointerException("callback is null");
        adapter = new TreeAdapter(callBack.createElements(), context);
        this.setAdapter(adapter);
        this.setCacheColorHint(Color.parseColor("#00000000"));
        this.setVerticalFadingEdgeEnabled(false);
//        this.setOnTouchListener(onTouch);
    }

    public static TreeElement createElement(String title) {
        return new TreeElement(title, null);
    }

    public static TreeElement createElement(String title, Object tag) {
        return new TreeElement(title, tag);
    }

    public static TreeElement createElement(String title, Object tag,
            TreeElement parent) {
        TreeElement e = new TreeElement(title, tag);
        if (parent != null)
            parent.addChild(e);
        return e;
    }

    public static TreeElement createElement(String title, TreeElement parent) {
        return createElement(title, null, parent);
    }
    
//    void setSelectedItemByTag1(Object tag) {
//        checkedItemByTag(adapter.elements, tag);
//        adapter.items = new ArrayList<TreeElement>();
//        adapter.createItems(adapter.elements);
//        adapter.notifyDataSetChanged();
//        if (selectedPosition != -1)
//            TreeView.this.setSelectionFromTop(selectedPosition, SELECTED_TOP);
//    }
//
//    private void checkedItemByTag1(List<TreeElement> es, Object tag) {
//        for (TreeElement e : es) {
//            if (e.hasChildren()) {
//                checkedItemByTag(e.children, tag);
//            } else {
//                if (callBack.equalByTag(tag, e.getTag())) {
//                    setParentExpend(e.parent);
//                    e.selected = true;
//                } else {
//                    e.selected = false;
//                }
//            }
//        }
//    }

//    private void setParentExpend(TreeElement e) {
//        e.expanded = true;
//        if (e.parent != null)
//            setParentExpend(e.parent);
//    }

    private class TreeAdapter extends BaseAdapter {
        private List<TreeElement> items;
        private List<TreeElement> elements;
  
        private Context context;
        
        public TreeAdapter(List<TreeElement> elements, Context context) {
            this.elements = elements;
            this.context = context;

            items = new ArrayList<TreeElement>();
            createItems(elements);
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int id) {
            return id;
        }

        @Override
        public View getView(int position, View convertView,
                ViewGroup paramViewGroup) {
            View view = LayoutInflater.from(context).inflate(
                    R.layout.list_item_icon_icon_text_toggle, null);
            final TreeElement elem = items.get(position);
 //           view.setOnClickListener(itemOnClick);
            view.setTag(items.get(position));

            if (elem.isSelected())
                view.setBackgroundColor(Color.parseColor("#FFFF33"));

            ImageView icon = (ImageView) view.findViewById(R.id.icon);
            icon.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View view) {
                    
                    if (elem.hasChildren()) {
                        // 展开了则关闭
                        if (elem.isExpanded()) {
                            clearExpand(elem);
                        }
                        // 没有展开则展开节点
                        else {
                            elem.setExpanded(true);
                        }
                        items = new ArrayList<TreeElement>();
                        createItems(elements);
                        TreeAdapter.this.notifyDataSetChanged();
                    } else {
                        callBack.elementSelected(elem);
                    }
                }
            });
            TextView text = (TextView) view.findViewById(R.id.text);

            int level = elem.getLevel();
            icon.setPadding(10 * level, 10, 0, 10);
            text.setText(elem.getTitle());
            text.setPadding(10, 10, 0, 10);

            if (elem.hasChildren()
                    && (elem.isExpanded() == false)) {
                icon.setImageResource( R.drawable.open);
                icon.setVisibility(View.VISIBLE);
            } else if (elem.hasChildren()
                    && (elem.isExpanded() == true)) {
            	 icon.setImageResource( R.drawable.close);
            	    icon.setVisibility(View.VISIBLE);
            } else if (!elem.hasChildren()) {
            	 icon.setImageResource( R.drawable.close);
                icon.setVisibility(View.INVISIBLE);
            }
            ToggleButton toggle = (ToggleButton) view.findViewById(R.id.toggle);
            if(!(elem.getTag() instanceof SecuredServer))
            	toggle.setVisibility(View.INVISIBLE);
            else
            {
            	final SecuredServer p = (SecuredServer)elem.getTag();
           		toggle.setChecked(p.getServerAccessController().isPermitted());
           		toggle.setOnCheckedChangeListener(new ToggleButton.OnCheckedChangeListener(){

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						p.getServerAccessController().setPermitted(isChecked);
						
					}
           			
           		});

            }
            
            ImageView devic = (ImageView) view.findViewById(R.id.entity_icon);
            Drawable dw = getDrawable(elem);
            if(dw == null)
            	devic.setVisibility(View.GONE);
            else
            	devic.setImageDrawable(dw);
            
            ImageView arrow = (ImageView) view.findViewById(R.id.arrow);
           
            if(elem.getTag() instanceof ClusterServer){
            	arrow.setVisibility(View.VISIBLE);
            	arrow.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {

						ClusterServer cs = (ClusterServer)elem.getTag();
                        Class<? extends Activity> type = ServerClusterActivityManager.getActivity(cs.getCluster());
						Intent i = new Intent(context,type);
                        i.setPackage(context.getPackageName());
						i.putExtra("deviceId", cs.getDevice().getId());
						
						i.putExtra("clusterId", cs.getCluster());
						context.startActivity(i);
					}
				});
            }else
            	arrow.setVisibility(View.GONE);
          
            
            return view;
        }
        
		Drawable getDrawable(TreeElement e){
			String icon = null;
			Object o =  e.getTag();
			if(o instanceof DeviceServer)
				icon =  ((DeviceServer)o).getDevice().getType();
			if(o instanceof ClusterServer)
				icon = ((ClusterServer)o).getCluster();
			if(icon != null && !icon.equals(""))
				return IconManager.getIconDrawable(context, icon);
			return null;
		}

        /**
         * 把子元素的所有expand属性清除
         * 
         * @param element
*/
        private void clearExpand(TreeElement element) {
            element.setExpanded(false);
            if (element.hasChildren())
                for (int i = 0; i < element.childCount(); i++)
                    if (element.getChild(i).hasChildren())
                        clearExpand(element.getChild(i));
        }

        /**
         * 创建所有的元素
         * 
         * @param elements
*/
        private void createItems(List<TreeElement> elements) {
            for (TreeElement e : elements)
                addItem(e);
        }

        /**
         * 在树中添加元素，当子元素是树节点时判断是否已经展开
         * 
         * @param element
*/
        private void addItem(TreeElement element) {
            items.add(element);
            if (element.selected)
                selectedPosition = items.size() - 1;
            if (element.hasChildren() && element.isExpanded())
                createItems(element.children);
        }

    }

    /**
     * 树元素
     * 
     * @author Administrator
     * 
*/
    public static class TreeElement {
        private String title;
        private int level;
        private TreeElement parent;
        private boolean expanded = false;
        private Object tag;
        private boolean selected;
        private List<TreeElement> children = new ArrayList<TreeElement>();

        protected TreeElement(String title, Object tag) {
            this.title = title;
            this.tag = tag;
        }

        public void addChild(TreeElement child) {
            children.add(child);
            child.setParent(this);
        }

        public int childCount() {
            return children.size();
        }

        public boolean hasChildren() {
            if (children.size() > 0)
                return true;
            return false;
        }

        public TreeElement getChild(int position) {
            if (position < 0 || position > children.size() - 1)
                return null;
            return children.get(position);
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        /**
         * 当前元素的等级，默认为1级，padding = 25 * level
         * 
         * @return
*/
        protected int getLevel() {
            level = 1;
            TreeElement parent = this.getParent();
            while (parent != null) {
                parent = parent.getParent();
                level++;
            }
            return level;
        }

        protected boolean isExpanded() {
            return expanded;
        }

        public void setExpanded(boolean expanded) {
            this.expanded = expanded;
        }

        public TreeElement getParent() {
            return parent;
        }

        public void setParent(TreeElement parent) {
            this.parent = parent;
        }

        public Object getTag() {
            return tag;
        }

        public void setTag(Object tag) {
            this.tag = tag;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }

    }

    public interface TreeCallBack {
        /**
         * 创建树元素
         * 
         * @return
*/
        public List<TreeElement> createElements();

        /**
         * 树根元素点击事件
         * 
         * @return
*/
        public void elementSelected(TreeElement element);

        /**
         * 比较两个tag是否相等
         * 
         * @param tag0
         *            树节点的tag
         * @param tag1
         *            指定比较的tag
         * @return
*/
        public Boolean equalByTag(Object tag0, Object tag1);
    }

}